import * as BusinessFieldApi from '@/api/setting/businessField'
import { camelCase } from 'lodash-es'
import type { FormRules } from 'element-plus'
import { SettingBusinessField as SettingBusinessFieldModel } from '@/model/setting/business/SettingBusinessField'
import { SettingBusinessFieldOption as SettingBusinessFieldOptionModel } from '@/model/setting/business/SettingBusinessFieldOption'
const { t } = useI18n() // 国际化
import { SettingBusinessModuleEnum } from '@/utils/constants'

export interface SettingBusinessFieldOptionEditModel extends SettingBusinessFieldOptionModel {
  id: number
}

export interface SettingBusinessFieldEditModel extends SettingBusinessFieldModel {
  options: SettingBusinessFieldOptionEditModel[]
}

const fieldTip = {
  [SettingBusinessModuleEnum.CUSTOMER]: 'customer.info.',
  [SettingBusinessModuleEnum.CUSTOMER_CONTACT]: 'customer.contact.',
  [SettingBusinessModuleEnum.CUSTOMER_FOLLOW]: 'customer.follow.'
}

const ruleValidator = (module: number) => {
  const checkCustomerImmutableField = (rule, value, callback) => {
    if (value === 0) {
      callback(new Error('请选择' + t(fieldTip[module] + rule.field)))
    } else {
      callback()
    }
  }
  return checkCustomerImmutableField
}

export const getBussinessModule = async (module: number) => {
  const moduleInfo = {
    immutableFields: new Map() as Map<string, SettingBusinessFieldEditModel>,
    customFields: [] as SettingBusinessFieldEditModel[],
    rules: {} as FormRules
  }
  const moduleFields = await BusinessFieldApi.getByModule(module)
  moduleFields.forEach((field) => {
    field.fieldName = camelCase(field.fieldName)
    if (!field.isShow) return
    if (field.isEditShow == false) {
      moduleInfo.immutableFields.set(field.fieldName, field)
      if (field.isMustFill) {
        moduleInfo.rules[field.fieldName] = [
          {
            validator: ruleValidator(module),
            type: 'number',
            required: true,
            trigger: 'change'
          }
        ]
      }
    } else {
      moduleInfo.customFields.push(field)

      if (field.isMustFill) {
        if (field.options.length == 0) {
          moduleInfo.rules[field.fieldName] = [
            {
              required: true,
              message: '请输入' + field.showName,
              type: 'string',
              trigger: 'blur'
            }
          ]
        } else {
          moduleInfo.rules[field.fieldName] = [
            {
              required: true,
              message: '请选择' + field.showName,
              type: 'string',
              trigger: 'change'
            }
          ]
        }
      }
    }
  })
  return moduleInfo
}
